<?php namespace module\button\controller;

use houdunwang\request\Request;
use houdunwang\wechat\WeChat;
use module\HdController;
use system\model\Button as ButtonModel;

class Button extends HdController
{

    public function index()
    {
        $field = ButtonModel::get();
        return $this->template('', compact('field'));
    }

    //添加回复
    public function post()
    {
        $id = Request::get('id');
        $model = ButtonModel::find($id) ?: new ButtonModel();
        if (IS_POST) {
            //p($_POST);die;
            $post = Request::post();
            if ($id) {
                $post['state'] = 0;
            }
            $model->save($post);
            return $this->setRedirect(url('button.index'))->success('操作成功');
        }
        //这里需要特殊考虑添加，在模板页面中button对应的就不存在，js报错
        if (!$id) {
            $model = ['title' => '', 'content' => '[]'];
        }
        return $this->template('', compact('model'));
    }

    /**
     * 删除
     *
     */
    public function del()
    {
        $id = Request::get('id');
        //p($id);die;
        //删除回复内容
        $model = ButtonModel::find($id);
        $model->destory();
        //成功提示
        return $this->setRedirect(url('button.index'))->success('操作成功');
    }

    public function send()
    {
        $id = Request::get('id');
        $data = ButtonModel::find($id)->content;
        //↑获取数据
        $button['button'] = json_decode($data, true);
        //↑装进数据        ↑将josn转为数组    符合微信菜单提交要求
//        p($button);
        $res = WeChat::instance('button')->create($button);
//        p($res);die;
        //↑菜单数据推送给微信
        if ($res['errcode'] == 0) {
            //↑报错提示 0成功
            Db::table('button')->where("id", $id)->update(['state' => 1]);
            //↑update 为菜单使用状态更新 1为使用中
            Db::table('button')->where("id", '<>', $id)->update(['state' => 0]);
            //↑将其余菜单使用状态还原
            return $this->setRedirect(url('button.index'))->success('菜单推送成功');
            //↑操作提示 返回列表
        }else{
            return $this->error('错误码：'.$res['errcode'].'错误消息'.$res['errmsg']);
        }

    }
}